<template>
  <div class="weekly-report-list">
    <section
      id="reportist"
      v-if="weekRecords.length"
      slot="pdf-content"
      v-infinite-scroll="onDebounceLoad"
      infinite-scroll-disabled="scrollDisabled"
    >
      <el-card
        class="box-card"
        :style="{margin: '0 auto 20px', width: printing ? '800px' : '100%'}"
        v-for="(weekRecord, index) in weekRecords"
        :key="index"
      >
        <div
          class="header"
          :class="printing ? 'printing' : ''"
        >
          <h2 style="
              text-align: center;
              color: #666;
              font-weight: 500;
              font-size: 20px;
            ">
            {{ getTitleContent(weekRecord)
            }}
          </h2>
          <div
            style="
              margin-top: 34px;
              padding: 0 8px 4px;
              display: flex;
              justify-content: space-between;
              border-bottom: 1px solid #ebeef5;
              font-size: 14px;
              color: #666;
            "
            class="unit-info"
          >
            <div>
              <span>单位（职务）：{{ `${weekRecord.records[0].department}（${weekRecord.records[0].label_name || ''}）` || "" }}</span>
              <span
                class="tbr"
                style="margin-left:30px"
                v-if="weekRecord.records[0].tbr !== null"
              >填报人：{{ `${weekRecord.records[0].tbr}` || "" }}</span>
              <span
                class="tbr"
                style="margin-left:30px"
                v-if="weekRecord.records[0].tbr_phone !== null"
              >联系方式：{{ `${weekRecord.records[0].tbr_phone}` || "" }}</span>
            </div>
            <span style="
                display: inline-block;
                position: absolute;
                top: 10px;
                font-size: 12px;
                color: #999;
                left: 26px;
              ">{{ weekRecord.records[0].week_range || "" }}</span>
            <span>填表日期：{{
                parseTime(weekRecord.records[0].create_time, "{y}年{m}月{d}日")
              }}</span>
          </div>
        </div>
        <yearly-report-table
          v-if="planType === '年'"
          :dataSource="weekRecord.records"
          :reportType="weekRecord.records[0].type"
          :printing="printing"
          :onAdd="() => handleAddRecord(weekRecord.records)"
          :onDelete="
            (selectedRecords) =>
              handleDeleteRecord(selectedRecords, weekRecord.records, index)
          "
          :onSubmit="() => handleSaveRecord(index, weekRecord.records)"
        />
        <weekly-report-table
          v-else
          :dataSource="weekRecord.records"
          :planType="planType"
          :printing="printing"
          :onAdd="() => handleAddRecord(weekRecord.records)"
          :onDelete="
            (selectedRecords) =>
              handleDeleteRecord(selectedRecords, weekRecord.records, index)
          "
          :onSubmit="() => handleSaveRecord(index, weekRecord.records)"
        />
      </el-card>
    </section>
    <el-empty
      v-if="!weekRecords.length && !loading"
      description="暂无数据"
    ></el-empty>
  </div>
</template>
<script>
import _ from "lodash";
import moment from "moment";
import { matchOriginArrayDiffence, uuid, parseTime } from "@/utils/index.js";
import { getYearReportName } from "../utils/plan";
import {
  createWeekSchedule,
  updateWeekSchedule,
  deleteWeekSchedule,
  createYearSchedule,
  updateYearSchedule,
  deleteYearSchedule
} from "@/api/plann";

export default {
  props: {
    weekRecords: {
      type: Array,
      default: () => []
    },
    planType: {
      type: String
    },
    loading: {
      type: Boolean
    },
    printing: {
      type: Boolean
    }
  },
  components: {
    WeeklyReportTable: () => import("./WeeklyReportTable.vue"),
    YearlyReportTable: () => import("./YearlyReportTable.vue")
  },
  watch: {
    weekRecords: {
      handler(newValue) {
        this.weeklyReportDataCopy = _.cloneDeep(newValue);
      },
      immediate: true
    }
  },
  computed: {
    tableTitle() {
      if (this.planType === "周") {
        return "周重点工作事项表";
      }
      return "月重点工作自评表";
    }
  },
  data() {
    return {
      weeklyReportDataCopy: [],
      currentMonthTemp: "工作事项：\n工作亮点：\n",
      nextMonthTemp: "工作事项：\n主要原因：\n整改措施：\n",
      scrollDisabled: false
    };
  },
  methods: {
    parseTime,
    // 初始化周、月报记录
    initRecord() {
      return {
        tempID: "new" + uuid(),
        current_week: this.planType === "周" ? "" : this.currentMonthTemp,
        next_week: this.planType === "周" ? "" : this.nextMonthTemp
      };
    },
    // 初始化年报记录
    initYearRecord() {
      return {
        tempID: "new" + uuid(),
        content_1: "",
        content_2: "",
        content_3: "",
        content_4: ""
      };
    },
    getTitleContent(weekRecord) {
      const { records, week_date, user__first_name } = weekRecord || [];
      const { username, type, year, date_type } = records[0] || {};
      if (this.planType === "年") {
        return getYearReportName(records[0], true);
      } else {
        return `${username}同志第${week_date}${this.tableTitle}`;
      }
    },
    onDebounceLoad: _.debounce(function() {
      this.$emit("onScrollLoad");
      this.scrollDisabled = true;
      setTimeout(() => {
        this.scrollDisabled = false;
      }, 2000);
    }, 300),
    // 点击添加，新增记录
    handleAddRecord(records) {
      if (this.planType === "年") {
        records.push(this.initYearRecord());
      } else {
        records.push(this.initRecord());
      }
    },
    // 点击删除
    async handleDeleteRecord(selectedRows, records, index) {
      const { newRecordsID, savedRecordsID } = this.getNewAndSavedRecords(
        selectedRows
      );
      if (this.planType === "年") {
        await this.fetchDeleteYearlyReport(savedRecordsID);
      } else {
        await this.fetchDeleteWeeklyReport(savedRecordsID);
      }
      const filterList = records.filter(
        item =>
          ![...newRecordsID, ...savedRecordsID].includes(item.id || item.tempID)
      );
      if (filterList.length) {
        this.weekRecords[index].records = filterList;
      } else {
        this.weekRecords.splice(index, 1);
      }
    },
    // 点击保存，新增、修改记录
    handleSaveRecord: _.debounce(function(index, target) {
      // return
      const { records: origin } = this.weeklyReportDataCopy[index];
      const { newRecords, savedRecords } = matchOriginArrayDiffence(
        origin,
        target
      );

      const { user, type, year, date_type, tbr, tbr_phone } = origin[0];
      const _tbr = tbr == null ? "-" : tbr;
      const _tbr_phone = tbr_phone == null ? "-" : tbr_phone;
      let week_date = null;
      let _isEmpty = false;
      if (this.planType == "月") {
        week_date = target[0].seq + '-28'
      } else if (this.planType == "周") {
        week_date = target[0].week_range
          .split("-")[0]
          .replace("年", "-")
          .replace("月", "-")
          .replace("日", "");
      } else {
        if (this.weekRecords[0].records[0].type == "keyWork") {
          for (let item in newRecords[0]) {
            if (newRecords[0][item] == "") {
              _isEmpty = true;
            }
          }
          for (let item in savedRecords[0]) {
            if (savedRecords[0][item] == "") {
              _isEmpty = true;
            }
          }
        } else {
          if (newRecords.length) {
            const isDelete = delete newRecords[0].content_4;
          }
          for (let item in newRecords[0]) {
            if (newRecords[0][item] == "") {
              _isEmpty = true;
            }
          }
          for (let item in savedRecords[0]) {
            if (savedRecords[0][item] == "") {
              _isEmpty = true;
            }
          }
        }
        week_date = moment(new Date()).format("YYYY-MM-DD");
      }
      if (_isEmpty) {
        this.$message.warning("内容不能为空！");
        return;
      }
      const totalRecords = [...newRecords, ...savedRecords];

      let isEmpty = false;
      // 判断表格当条记录是否为空
      if (this.planType === "年") {
        isEmpty = totalRecords.some(row => {
          let flag = false;
          Object.keys(row).forEach(key => {
            if (key !== "tempID" && row[key]) {
              flag = true;
            }
          });
          return !flag;
        });
      } else {
        isEmpty = totalRecords.some(item => !item.current_week);
      }

      if (isEmpty) {
        this.$message.info("工作情况记录不能为空记录");
        return;
      }

      if (!newRecords.length && !savedRecords.length) {
        this.$message.info("没有修改内容待提交");
        return;
      }
      //如果有新增记录
      if (newRecords.length) {
        if (this.planType === "年") {
          const _newRows = newRecords.map(row => {
            return {
              ...row,
              type,
              user,
              year,
              date_type,
              tbr: _tbr,
              tbr_phone: _tbr_phone
            };
          });
          this.fetchCreateYearlyReport(_newRows);
        } else {
          const _newRows = newRecords.map(row => {
            return {
              ...row,
              week_date,
              type: this.planType,
              user,
              tbr: _tbr,
              tbr_phone: _tbr_phone
            };
          });
          this.fetchCreateWeeklyReport(_newRows);
        }
      }
      // 如果更新记录
      if (savedRecords.length) {
        if (this.planType === "年") {
          this.fetchUpdateYearlyReport(savedRecords);
        } else {
          this.fetchUpdateWeeklyReport(savedRecords);
        }
      }
    }, 300),
    // 通过tempID 筛选新旧数据，返回记录以及id
    getNewAndSavedRecords(records) {
      const newRecords = [];
      const savedRecords = [];
      const newRecordsID = [];
      const savedRecordsID = [];

      records.forEach(record => {
        const { id, tempID } = record;
        if (tempID) {
          newRecords.push(record);
          newRecordsID.push(tempID);
        } else {
          savedRecords.push(record);
          savedRecordsID.push(id);
        }
      });
      return {
        newRecords,
        newRecordsID,
        savedRecords,
        savedRecordsID
      };
    },
    // 提交创建周月报记录请求
    async fetchCreateWeeklyReport(newRecords) {
      const { data } = await createWeekSchedule(newRecords);
      if (data) {
        this.$message.success("保存成功");
        this.$emit("onReloadfetch");
      }
    },
    // 提交编辑周月报记录请求
    fetchUpdateWeeklyReport(updateRecords) {
      const reqList = updateRecords.map(record => {
        const { id, current_week, next_week } = record;
        return new Promise(async (resolve, reject) => {
          await updateWeekSchedule(id, { current_week, next_week });
          resolve();
        });
      });
      Promise.all(reqList).then(res => {
        this.$message.success("修改成功");
        this.$emit("onReloadfetch");
      });
    },
    // 提交周月报删除请求
    fetchDeleteWeeklyReport(ids) {
      if (!ids.length) return;
      const reqList = ids.map(id => {
        return new Promise(async (resolve, reject) => {
          await deleteWeekSchedule(id);
          resolve();
        });
      });
      Promise.all(reqList).then(res => {
        this.$message.success("删除成功");
        this.$emit("onReloadfetch");
      });
    },
    // 提交创建年报记录请求
    async fetchCreateYearlyReport(newRecords) {
      const { data } = await createYearSchedule(newRecords);
      if (data) {
        this.$message.success("保存成功");
        this.$emit("onReloadfetch");
      }
    },
    // 提交编辑年报记录请求
    fetchUpdateYearlyReport(updateRecords) {
      const reqList = updateRecords.map(record => {
        const { id, content_1, content_2, content_3, content_4 } = record;
        return new Promise(async (resolve, reject) => {
          await updateYearSchedule(id, {
            content_1,
            content_2,
            content_3,
            content_4
          });
          resolve();
        });
      });
      Promise.all(reqList).then(res => {
        this.$message.success("修改成功");
        this.$emit("onReloadfetch");
      });
    },
    // 提交年报删除请求
    fetchDeleteYearlyReport(ids) {
      if (!ids.length) return;
      const reqList = ids.map(id => {
        return new Promise(async (resolve, reject) => {
          await deleteYearSchedule(id);
          resolve();
        });
      });
      Promise.all(reqList).then(res => {
        this.$message.success("删除成功");
        this.$emit("onReloadfetch");
      });
    }
  }
};
</script>
<style lang="scss">
.weekly-report-list {
  margin: 20px;
  .box-card {
    max-width: 1200px;

    .printing {
      h2,
      .extra {
        color: #000;
      }
    }
  }
  .el-card__body {
    position: relative;
  }
  @media screen and (max-width: 500px) {
    .unit-info {
      font-size: 12px !important;
    }
    .el-card__body {
      padding: 20px 10px;
    }
    .tbr {
      display: block;
      margin-left: 0px !important;
    }
  }
}
</style>